package lambda.lambda_complex_demo;

import lambda.Apple;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.Predicate;

/**
 * Description: 复合lambda的使用
 *
 * @author code-worker
 * @date 2021/10/09 21:44
 */
public class Lambda {

    private static List<Apple> apples;

    //初始化数据
    static {
        apples = new ArrayList<>();
        apples.add(new Apple(100, "red"));
        apples.add(new Apple(200, "green"));
    }

    /**
     * task: 比较复合
     * @author code-worker
     * @date 2021/10/9 21:51
     */
    void compareComplex(){
        //逆序
        apples.sort(Comparator.comparing(Apple::getWeight).reversed());
        //比较器链
        apples.sort(Comparator.comparing(Apple::getWeight).reversed()
                .thenComparing(Apple::getColor));
    }

    /**
     * task: 谓语复合
     * @author code-worker
     * @date 2021/10/9 22:03
     */
    void predicateComplex(){
        Predicate<Apple> redApples = apple -> "red".equals(apple.getColor());
        Predicate<Apple> heavyApples = apple -> apple.getWeight() > 150;
        //非
        Predicate<Apple> notRedApple = redApples.negate();
        //与
        Predicate<Apple> redAndHeavyApples = redApples.and(heavyApples);
        //或
        Predicate<Apple> redOrHeavyApples = redApples.or(heavyApples);
    }

    /**
     * task: 函数复合
     * @author code-worker
     * @date 2021/10/9 22:05
     */
    void functionComplex(){
        Function<Integer, Integer> add = i -> i + 1;
        Function<Integer, Integer> pow = i -> i * 2;
        Function<Integer, Integer> andThen = add.andThen(pow);
        // (1+1)*2
        System.out.println(andThen.apply(1));

        Function<Integer, Integer> compose = add.compose(pow);
        // 1*2+1
        System.out.println(compose.apply(1));
    }

    /**
     * task: 消费复合
     * @author code-worker
     * @date 2021/10/9 22:24
     */
    void consumerComplex(){
        Consumer<Apple> appleColor = apple -> System.out.println(apple.getColor());
        Consumer<Apple> appleWeight = apple -> System.out.println(apple.getWeight());
        Consumer<Apple> appleColorAndWeight = appleColor.andThen(appleWeight);
        appleColorAndWeight.accept(new Apple(100, "red"));
    }

    public static void main(String[] args) {
        Lambda lambda = new Lambda();
        lambda.consumerComplex();
    }
}
